import { h } from 'vue';
import { Switch } from 'ant-design-vue';
import { getRoleSelectList, checkUsername, setAdminStatus } from '@/api/app/setting';
import { BasicColumn, FormSchema } from '@/components/Table';
import { useMessage } from '@/hooks/web/useMessage';

export const columns: BasicColumn[] = [
  {
    title: '姓名',
    dataIndex: 'true_name',
    width: 120,
  },
  {
    title: '账号',
    dataIndex: 'username',
    width: 120,
  },
  {
    title: '电话',
    dataIndex: 'phone',
    width: 120,
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    width: 180,
  },
  {
    title: '角色',
    dataIndex: 'roles_name',
    width: 120,
  },
  {
    title: '最后一次登录时间',
    dataIndex: '_last_time',
    width: 180,
    // format: (record) => {
    //   return record ? Dayjs.unix(record).format('YYYY-MM-DD hh:mm:ss') : '';
    // },
  },
  {
    title: '最后一次登录ip',
    dataIndex: 'last_ip',
    width: 120,
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 120,
    customRender: ({ record }) => {
      if (!Reflect.has(record, 'pendingStatus')) {
        record.pendingStatus = false;
      }
      return h(Switch, {
        checked: record.status === 1,
        checkedChildren: '启用',
        unCheckedChildren: '禁用',
        loading: record.pendingStatus,
        onChange(checked: boolean) {
          record.pendingStatus = true;
          const newStatus = checked ? 1 : 0;
          const { createMessage } = useMessage();
          setAdminStatus(record.id, newStatus)
            .then(() => {
              record.status = newStatus;
              createMessage.success(`修改成功`);
            })
            .catch(() => {
              createMessage.error('修改失败');
            })
            .finally(() => {
              record.pendingStatus = false;
            });
        },
      });
    },
  },
];

export const searchFormSchema: FormSchema[] = [
  {
    field: 'name',
    label: '搜索',
    component: 'Input',
    colProps: { span: 8 },
    componentProps: {
      placeholder: '请输入姓名或者账号',
    },
  },
  {
    field: 'status',
    label: '状态',
    component: 'Select',
    componentProps: {
      options: [
        { label: '启用', value: '1' },
        { label: '停用', value: '0' },
      ],
    },
    colProps: { span: 8 },
  },
];

export const adminFormSchema: FormSchema[] = [
  {
    field: 'username',
    label: '用户名',
    component: 'Input',
    helpMessage: ['本字段演示异步验证', '不能输入带有admin的用户名'],
    rules: [
      {
        required: true,
        message: '请输入用户名',
      },
      {
        validator(_, value) {
          return new Promise((resolve, reject) => {
            checkUsername(value)
              .then(() => resolve())
              .catch((err) => {
                reject(err.message || '验证失败');
              });
          });
        },
      },
    ],
  },
  {
    field: 'password',
    label: '密码',
    component: 'InputPassword',
    required: true,
    ifShow: false,
  },
  {
    label: '角色',
    field: 'role',
    component: 'ApiSelect',
    componentProps: {
      api: getRoleSelectList,
      labelField: 'roleName',
      valueField: 'roleValue',
    },
    required: true,
  },
];

export const formSchema: FormSchema[] = [
  {
    field: 'id',
    label: 'ID',
    component: 'Input',
    show: false,
  },
  {
    field: 'username',
    label: '用户名',
    component: 'Input',
    rules: [
      {
        required: true,
        message: '请输入正确的账号',
      },
      {
        min: 4,
        max: 12,
        message: '请设置用户名长度4-12位',
      },
    ],
  },
  {
    field: 'true_name',
    label: '真实姓名',
    component: 'Input',
    required: true,
  },
  {
    field: 'password',
    label: '密码',
    component: 'InputPassword',
    rules: [
      {
        required: true,
        message: '请输入密码',
      },
      {
        min: 6,
        max: 12,
        message: '请设置密码长度6-12位',
      },
    ],
  },
  {
    field: 'conf_password',
    label: '确认密码',
    component: 'InputPassword',
    dynamicRules: ({ values }) => {
      return [
        {
          required: true,
          validator: (_, value) => {
            if (!value) {
              return Promise.reject('密码不能为空');
            }
            if (value !== values.password) {
              return Promise.reject('两次输入的密码不一致!');
            }
            return Promise.resolve();
          },
        },
      ];
    },
  },
  {
    field: 'phone',
    label: '手机号码',
    component: 'Input',
    rules: [
      {
        required: true,
        validator: (_, value) => {
          const phone = /^1[3456789]\d{9}$/;
          if (!value) {
            return Promise.reject('手机号不可为空');
          }
          if (phone.test(value)) {
            return Promise.resolve();
          } else {
            return Promise.reject('手机号码格式不正确!');
          }
        },
      },
    ],
  },
  // TODO: 角色多选
  {
    field: 'roles',
    label: '角色',
    component: 'Select',
    required: true,
  },
  {
    field: 'tel',
    label: '电话号码',
    component: 'Input',
  },
  // TODO: 上传组件
  // {
  //   field: 'face',
  //   label: '头像',
  //   component: 'Upload',
  // },
  {
    field: 'email',
    label: '邮箱',
    component: 'Input',
    rules: [
      {
        validator: (_, value) => {
          const mail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
          if (value) {
            if (mail.test(value)) {
              return Promise.resolve();
            } else {
              return Promise.reject('邮箱格式不正确!');
            }
          }
        },
      },
    ],
  },
  {
    field: 'dept_id',
    label: '所属部门',
    component: 'TreeSelect',
    componentProps: {
      fieldNames: {
        label: 'dept_name',
        key: 'id',
        value: 'id',
      },
      getPopupContainer: () => document.body,
    },
  },
  {
    field: 'status',
    label: '状态',
    component: 'RadioButtonGroup',
    defaultValue: 1,
    componentProps: {
      options: [
        { label: '启用', value: 1 },
        { label: '禁用', value: 0 },
      ],
    },
  },
  {
    field: 'remark',
    label: '备注',
    component: 'InputTextArea',
    colProps: {
      lg: 32,
      md: 24,
    },
    componentProps: {
      rows: 4,
    },
  },
];
